package de.dubiel.plung.client.pages.start;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.inject.Inject;

import de.dubiel.plung.client.gin.ClientGinjector;
import de.dubiel.plung.shared.dao.HighScore;
import de.dubiel.plung.shared.dao.User;

public class StartViewImpl extends Composite implements StartView {
    private final static Logger LOG = Logger.getLogger(StartViewImpl.class.getName());
    private static ActionUiBinder uiBinder = GWT.create(ActionUiBinder.class);

    interface ActionUiBinder extends UiBinder<Widget, StartViewImpl> {
    }

    private ClientGinjector clientGinjector;

    @UiField
    HighScoreList highScoreTable;
    @UiField
    SimplePager pager;

    @Inject
    public StartViewImpl(ClientGinjector clientGinjector) {
        this.clientGinjector = clientGinjector;
        initWidget(uiBinder.createAndBindUi(this));
        AsyncDataProvider<User> provider = new AsyncDataProvider<User>() {

            @Override
            protected void onRangeChanged(HasData<User> display) {
                final int start = display.getVisibleRange().getStart();
                int length = display.getVisibleRange().getLength();
                StartViewImpl.this.clientGinjector.getUserService().getHighScoreList(start, length, new AsyncCallback<HighScore>() {

                    @Override
                    public void onFailure(Throwable caught) {
                        LOG.log(Level.SEVERE, caught.getMessage(), caught);
                    }

                    @Override
                    public void onSuccess(HighScore result) {
                        if (result.getHighScoreList().isEmpty())
                            updateRowCount(0, true);
                        else {
                            updateRowCount(result.getNumHighScoreEntrys(), true);
                            updateRowData(start, result.getHighScoreList());
                        }
                    }
                });
            }
        };

        // Connect the table to the data provider.
        provider.addDataDisplay(highScoreTable);

        pager.setDisplay(highScoreTable);
    }

    @Override
    public void refreshHighScore() {
        pager.firstPage();
    }
}